import { createRouter, createWebHistory } from 'vue-router';
// 管理员相关  -- 默认登录密码"admin"
import Layout from "../views/admin/LayoutMenu.vue";
import Home from '../views/admin/HomePage.vue';
import Users from '../views/admin/UserList.vue';
import Photos from '../views/admin/PhotoList.vue';
import Posts from '../views/admin/PostList.vue';
import Events from '../views/admin/EventList.vue';
import Login from '../views/admin/LoginPage.vue';
// 用户相关
import UserLayout from "../views/user/LayoutMenu.vue";
import UserRegister from '../views/user/RegisterPage.vue';
import UserLogin from '../views/user/LoginPage.vue';
import UserPhotoList from '../views/user/PhotoList.vue';
import UserPostList from '../views/user/PostList.vue';
import UserEventList from '../views/user/EventList.vue';
import UserProfile from '../views/user/UserProfile.vue';

const routes = [
  ///////////////////// 用户相关页面 /////////////////////
  { path: '/', redirect: '/user/login' },
  { path: '/user/login', name: 'UserLogin', component: UserLogin },
  { path: '/register', name: 'Register', component: UserRegister },

  // 使用 Layout 的页面
  {
    path: '/user/',
    component: UserLayout,
    children: [
      { path: 'photos', name: 'UserPhotoList', component: UserPhotoList },
      { path: 'posts', name: 'UserPostList', component: UserPostList },
      { path: 'events', name: 'UserEventList', component: UserEventList },
      { path: 'profile', name: 'UserProfile', component: UserProfile },
    ],
  },


  ///////////////////// 管理员相关页面 /////////////////////
  // 独立页面
  { path: '/login', name: 'Login', component: Login },
  
  // 使用 Layout 的页面
  {
    path: '/',
    component: Layout,
    children: [
      { path: 'home', name: 'Home', component: Home },
      { path: 'users', name: 'Users', component: Users },
      { path: 'photos', name: 'Photos', component: Photos },
      { path: 'posts', name: 'Posts', component: Posts },
      { path: 'events', name: 'Events', component: Events },
    ],
  },

];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('token'); // 假设使用 token 存储登录状态
  // 如果路由需要登录保护
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login'); // 未登录时跳转到登录页面
  } else if (to.path === '/login' && isAuthenticated) {
    next('/home'); // 如果已登录，访问登录页时跳转到首页
  } else {
    next(); // 正常导航
  }
});

export default router;
